//
//  CalendarViewController.swift
//  VenusTodo
//
//  Created by 文显庆 on 2021/10/23.
//

// 日历视图 UiKit

import UIKit
import CVCalendar

class CalendarViewController: UIViewController {
    
    //星期菜单栏
    var menuView: CVCalendarMenuView!
    
    //日历主视图
    var calendarView: CVCalendarView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置标题
        let currentCalendar: Calendar = Calendar.init(identifier: .gregorian)
        self.view.backgroundColor = UIColor(red: 239.0/255, green: 239.0/255, blue: 239.0/255, alpha: 1.0)
        self.menuView = CVCalendarMenuView(frame: CGRect(x: 20, y: 70, width: 374, height: 15))
        self.calendarView = CVCalendarView(frame: CGRect(x: 20, y: 90, width: 374, height: 320))
        self.calendarView.calendarAppearanceDelegate = self
        self.calendarView.calendarDelegate = self
        self.calendarView.animatorDelegate = self
        self.menuView.menuViewDelegate = self
        self.view.addSubview(menuView)
        self.view.addSubview(calendarView)
        self.title = CVDate(date: Date(), calendar: currentCalendar).globalDescription
        
        
        
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.menuView.commitMenuViewUpdate()
        self.calendarView.commitCalendarViewUpdate()
    }
}

extension CalendarViewController: CVCalendarViewDelegate, CVCalendarMenuViewDelegate {
    func presentationMode() -> CalendarMode {
        return .monthView
    }

    //将周一设置为每周的开始
    func firstWeekday() -> Weekday {
        return .monday
    }
    func dayOfWeekTextColor(by weekday: Weekday) -> UIColor {
        return weekday == .sunday ? UIColor.red : UIColor.black
    }
    
    func shouldShowWeekdaysOut() -> Bool {
        return true
    }
    
    func shouldAnimateResizing() -> Bool {
        return true
    }
    
    //切换月的时候日历是否自动选择某一天（本月为今天，其它月为第一天）
     func  shouldAutoSelectDayOnMonthChange() ->  Bool  {
         return  false
     }
    
    //添加一个代理方法，用来设置是否选中某个日期视图
    private func shouldSelectDayView(dayView: DayView) -> Bool {
        return false
    }
    
    //添加一个代理方法，用来响应某个日期被选中的事件
    func didSelectDayView(_ dayView: CVCalendarDayView, animationDidFinish: Bool) {
        
        let date = dayView.date.convertedDate()!
        // 创建一个日期格式器
        let dformatter = DateFormatter()
        dformatter.dateFormat = "yyyy年MM月dd日"
        let message = "\(dformatter.string(from: date))"
        
        var isBusy: Bool = false //这天是否有事
        
        var showMessage: String = "您在\n\(message)\n之前未完成的任务有\n"
        
        for i in Things {
            if(message == i.formatedDateEnd) {
                isBusy = true
                showMessage += "\(i.name)\n"
            }
        }
        showMessage += "🐛🐛🐛！"
        /*
        //获取日期
        let date = dayView.date.convertedDate()!
        // 创建一个日期格式器
        let dformatter = DateFormatter()
        dformatter.dateFormat = "yyyy年MM月dd日"
        let message = "当前选择的日期是：\(dformatter.string(from: date))"
        */
        //将选择的日期弹出显示
        
        if isBusy == true {
        } else {
            showMessage = "您在\n\(message)之前\n没有需要完成的任务🏄🏼‍♂️"
        }
        let alertController = UIAlertController(title: "", message: showMessage,preferredStyle: .alert)
        let okAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
        
    }
    
    func topMarker(shouldDisplayOnDayView dayView: CVCalendarDayView) -> Bool {
        return false
    }
    
    //添加一个代理方法，用来设置是否允许在日期的上方，显示一个点标识
    func dotMarker(shouldShowOnDayView dayView: CVCalendarDayView) -> Bool {
        return false
    }
    
    func dotMarker(colorOnDayView dayView: CVCalendarDayView) -> [UIColor] {
        let red = CGFloat(arc4random_uniform(600) / 255)
        let green = CGFloat(arc4random_uniform(600) / 255)
        let blue = CGFloat(arc4random_uniform(600) / 255)
        let color = UIColor(red: red, green: green, blue: blue, alpha: 1)
        
        let numberOfDots = Int(arc4random_uniform(3) + 1)
        switch (numberOfDots) {
        case 2:
            return [color, color]
        case 3:
            return [color, color, color]
        default:
            return [color]
        }
    }
    
    func dotMarker(shouldMoveOnHighlightingOnDayView dayView: CVCalendarDayView) -> Bool {
        return false
    }
    
    func dotMarker(sizeOnDayView dayView: CVCalendarDayView) -> CGFloat {
        return 13
    }
    
    func weekdaySymbolType() -> WeekdaySymbolType {
        return .short
    }
    
    func selectionViewPath() -> ((CGRect) -> (UIBezierPath)) {
        return {
            UIBezierPath(rect: CGRect(x: 0, y: 0, width: $0.width, height: $0.height))
        }
    }
    
    func shouldShowCustomSingleSelection() -> Bool {
        return false
    }
    
    //添加一个代理方法，用来设置显示在日期上的辅助视图
    func preliminaryView(viewOnDayView dayView: DayView) -> UIView {
        //初始化一个辅助视图，设置其显示区域和日期视图相同，并且形状为圆形。
        let circleView = CVAuxiliaryView(dayView: dayView, rect: dayView.frame, shape: CVShape.circle)
        circleView.fillColor = .colorFromCode(0xbce672)
        return circleView
    }
    
    func preliminaryView(shouldDisplayOnDayView dayView: DayView) -> Bool {
        if let date = dayView.date?.convertedDate() {
        // 创建一个日期格式器
        let dformatter = DateFormatter()
        dformatter.dateFormat = "yyyy年MM月dd日"
        let message = "\(dformatter.string(from: date))"
        for i in Things {
            if(message == i.formatedDateEnd) {
                return true
            }
        }
    }
        return false
    }
    
    func supplementaryView(viewOnDayView dayView: DayView) -> UIView {
        let pi = Double.pi
        let ringSpacing: CGFloat = 3.0
        let ringInsetWidth: CGFloat = 1.0
        let ringVerticaOffset: CGFloat = 1.0
        let ringLineWidth: CGFloat = 1.0
        var ringLayer: CAShapeLayer!
        let ringLineColour: UIColor = UIColor.purple
        let newView = UIView(frame: dayView.bounds)
        let diameter: CGFloat = (newView.bounds.width) - ringSpacing
        let radius: CGFloat = diameter / 2.0
        let rect = CGRect(x: newView.frame.midX-radius, y: newView.frame.midY-radius-ringVerticaOffset, width: diameter, height: diameter)
        ringLayer = CAShapeLayer()
        newView.layer.addSublayer(ringLayer)
        ringLayer.fillColor = nil
        ringLayer.lineWidth = ringLineWidth
        ringLayer.strokeColor = ringLineColour.cgColor
        let ringLineWidthInset: CGFloat = CGFloat(ringLineWidth/2.0) + ringInsetWidth
        let ringRect: CGRect = rect.insetBy(dx: ringLineWidthInset, dy: ringLineWidthInset)
        let centrePoint: CGPoint = CGPoint(x: ringRect.midX, y: ringRect.midY)
        let startAngle: CGFloat = CGFloat(-pi/2.0)
        let endAngle: CGFloat = CGFloat(pi * 2.0) + startAngle
        let ringPath: UIBezierPath = UIBezierPath(arcCenter: centrePoint, radius: ringRect.width/2.0, startAngle: startAngle, endAngle: endAngle, clockwise: true)
        ringLayer.path = ringPath.cgPath
        ringLayer.frame = newView.layer.bounds
        return newView
    }
    
    //添加一个代理方法，用来设置在何种情况下，允许显示辅助视图。
    //shouldShowOnDayView dayView: CVCalendarDayView
    func supplementaryView(shouldDisplayOnDayView dayView: CVCalendarDayView) -> Bool {
        
        return false
    }
    
    func dayOfWeekTextColor() -> UIColor {
        return UIColor.black
    }
    
    func dayOfWeekBackGroundColor() -> UIColor {
        return UIColor.clear
    }
}
